package com.gitee.mazhenggg.demo.auth.security;


import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Date;
import java.util.Optional;

@Slf4j
public class CustomUsernamePasswordAuthenticationProvider extends DaoAuthenticationProvider {


//	@Override
//	protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
//		log.info("增加自己额外的校验");
//		super.additionalAuthenticationChecks(userDetails, authentication);
//	}

	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		RuntimeException exception = new BadCredentialsException("账号或密码错误");

		// 可以处理异常
		String username = authentication.getName();
		log.debug("username:"+username);
		//LoginConfig loginConfig = sysConfigService.getLoginConfig();
		//this.loginFailedCount = Optional.ofNullable(loginConfig.getPasswordFailedCount()).orElse(0);
		//this.lockTime = Optional.ofNullable(loginConfig.getPasswordFailedLocktime()).orElse(0);
		try {
			return super.authenticate(authentication);
		} catch (BadCredentialsException e) {
			log.debug("用户：{}，认证失败",username);
//			SecurityUser securityUser = userService.getByUniqueId(username);
//			if (null != securityUser) {
//				if (0 != loginFailedCount && 0 != lockTime) {
//					Date currDate = new Date();
//					// 获取当前用户登录失败次数（redis），系统允许的失败次数
//					// 1.redis增加登录失败次数
//					long failedLoginAttempts = addFailedLoginAttempt(securityUser);
//					if (failedLoginAttempts >= loginFailedCount) {
//						securityUser.setIsLocked(CommonEnum.GLOBAL_YN.YES.getCode());
//						securityUser.setLockDate(currDate);
//						exception = new LockedException("用户账号已经被锁定，请" + lockTime + "分钟后再试");
//						// 更新用户
//						userService.updateUserLocked(username, CommonEnum.GLOBAL_YN.YES.getCode(), currDate, "密码错误次数超过" + failedLoginAttempts + "次");
//						// 锁定以后直接将失败次数清空
//						redisUtils.del(getFailedLoginAttemptKey(username));
//					} else {
//						exception = new BadCredentialsException("账号或密码错误，您还有" + (loginFailedCount - failedLoginAttempts) +"次机会");
//					}
//				}
//			}
		} catch (UsernameNotFoundException e) {
			log.debug("用户，{}，不存在", username);
			e.printStackTrace();
			exception = e;
		} catch (LockedException e) {
			log.debug("用户，{}，已被锁定", username);
//			SecurityUser securityUser = userService.getByUniqueId(username);
//			DateTime begin = new DateTime(new Date());
//			DateTime end = new DateTime(securityUser.getLockDate());
//			Period period = new Period(begin, end, PeriodType.minutes());
//			int diff = period.getMinutes();
//			int minute = lockTime + diff;
//			// 小于等于0，说明已经超过了解锁时间
//			if (minute <= 0) {
//				exception = new LockedException("用户账号已经被锁定，自动解锁失败，请联系管理员");
//			} else {
//				exception = new LockedException("用户账号已经被锁定，请" +minute+ "分钟后再试");
//			}
		}
		throw exception;

	}

//	private long addFailedLoginAttempt(SecurityUser securityUser) {
//		String username = securityUser.getUsername();
//		String failedLoginAttemptKey = getFailedLoginAttemptKey(username);
//		long currFailedLoginAttempts = redisUtils.incr(failedLoginAttemptKey);
//		redisUtils.expire(failedLoginAttemptKey,  lockTime * 60);
//		return currFailedLoginAttempts;
//	}
//
//	public static String getFailedLoginAttemptKey(String username) {
//		return NAMESPACE +":" + username;
//	}
}
